<script setup lang="ts">
import { loginByPasswordApi } from "@/apis/user"
import { useUserStore } from "@/stores/user"
import type { LoginPasswordParams } from "@/types/user"
import { ref } from "vue"

// 定义页面配置项
defineOptions({
  options: {
    styleIsolation: "shared",
  },
})

// 初始化登录表单数据，包含手机号和密码字段
const formData = ref<LoginPasswordParams>({
  mobile: "13230000069",
  password: "",
})

// 获取表单实例，用于后续的表单验证操作
const form = ref<UniHelper.UniFormsInstance>()

// 定义表单验证规则，包括手机号和密码的验证规则
const rules: UniHelper.UniFormsRules = {
  mobile: {
    rules: [
      { required: true, errorMessage: "手机号不能为空" },
      { pattern: "^1[3-9]\\d{9}$", errorMessage: "手机号格式不正确" },
    ],
  },
  password: {
    rules: [
      { required: true, errorMessage: "密码不能为空" },
      { pattern: "^[a-zA-Z0-9_-]{8,16}$", errorMessage: "密码格式不正确" },
    ],
  },
}

// 定义是否同意用户协议的响应式变量
const isAgree = ref(false)

/**
 * 提交表单的异步函数
 * 此函数在用户点击登录按钮时触发，负责验证表单数据并处理登录逻辑
 */
const onsubmit = async () => {
  try {
    // 验证表单数据是否符合规则
    await form.value?.validate?.()
    // 检查用户是否同意用户协议
    if (!isAgree.value) {
      return uni.showToast({ title: "请勾选用户协议", icon: "none" })
    }
    // 调用登录API，发送登录请求
    const res = await loginByPasswordApi(formData.value)
    // 获取用户状态管理实例，用于存储用户登录状态
    const userStore = useUserStore()
    // 将登录返回的token保存到用户状态中
    userStore.setToken(res.token)
    // 将用户ID保存到用户状态中
    userStore.setUserId(res.id)
    // 显示登录成功提示
    uni.showToast({ title: "登录成功" })
    // 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
    uni.switchTab({ url: "/pages/index/index" })
  } catch (error) {
    // 捕获并处理登录过程中出现的错误
    console.log(error)
  }
}
</script>
<template>
  <uni-forms class="login-form" ref="form" :rules="rules" :model="formData">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
        v-model="formData.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onsubmit()">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" ">
      忘记密码？
    </navigator>
  </uni-forms>
</template>
<style lang="scss">
@import "./styles.scss";
</style>
